package com.cindata

import com.cindata.dictionary.AttachmentType
import com.cindata.dictionary.MortgageCollectionType
import grails.converters.JSON
import grails.gorm.transactions.Transactional
import org.grails.web.util.WebUtils
import org.springframework.security.access.annotation.Secured

import java.text.SimpleDateFormat

@Secured(['permitAll'])
@Transactional
class CollectionApiController
{
    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]
    def riskWarningService
    def workflowInstanceService
    
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss")

    def index()
    {
    }

    /**
     * 催收结果回调
     **/
    def collectionCallBack()
    {
        //接收参数
        def params = readReqJSONParams(request.getReader())

        println params

        MortgageCollectionType mortgageCollectionType
        //催收类型
        if("电话催收".equals(params?.collectorType)){
            mortgageCollectionType = MortgageCollectionType.findByName("电话催收")
        }
        if("短信催收".equals(params?.collectorType)){
            mortgageCollectionType = MortgageCollectionType.findByName("短信催收")
        }
        if("信函催收".equals(params?.collectorType)){
            mortgageCollectionType = MortgageCollectionType.findByName("邮件催收")
        }
        if("现场催收".equals(params?.collectorType)){
            mortgageCollectionType = MortgageCollectionType.findByName("上门催收")
        }

        //根据工作流id来查找出riskWarning
        def riskWarning = RiskWarning.findById(Long.parseLong(params.taskNumber))

        if(!riskWarning )
        {
            render([message: "失败,任务编号不存在", code: '1'] as JSON)
            return
        }

        //催收实际开始时间和完成时间
        riskWarning?.actualStartTime = sdf.parse(params?.realityStartTime)
        riskWarning?.actualEndTime = sdf.parse(params?.realityEndTime)
        riskWarning.save(flush:true)

        //创建催收记录
        MortgageCollectionRecord mortgageCollectionRecord = new MortgageCollectionRecord()
        mortgageCollectionRecord.collectionType = mortgageCollectionType
        mortgageCollectionRecord.fullName = params?.collectorName
        mortgageCollectionRecord.repaymentPlan = params?.repaymentPlan
        mortgageCollectionRecord.reasonOfOverdue = params?.overdueReason
        mortgageCollectionRecord.collectionResult = params?.collectorResult
        mortgageCollectionRecord.riskWarning = riskWarning
        mortgageCollectionRecord.mortgage = riskWarning?.mortgage
        mortgageCollectionRecord.department = riskWarning?.disposalDepartment?.name
        mortgageCollectionRecord.createdDate = new Date()
        mortgageCollectionRecord.save(flush:true)

        //短信截图
        if(params?.smsMessageUrl){
            int i = 0
            params?.smsMessageUrl.each{
                String urlNameString = it
                def fileOrgName = urlNameString.split("\\/")[-1]
                Attachment attachment = new Attachment()
                attachment.type = AttachmentType.findByName("短信截图")
                attachment.riskWarning = riskWarning
                attachment.fileName = fileOrgName
                attachment.fileUrl = it
                attachment.description = fileOrgName?.split('\\.')[0]
                attachment.save(flush:true)
                i++
                println "第"+i+"条短信截图处理成功"
            }
        }
        //电话录音
        if(params?.phoneRecording){
            int i = 0
            params?.phoneRecording.each{
                String urlNameString = it
                def fileOrgName = urlNameString.split("\\/")[-1]
                Attachment attachment = new Attachment()
                attachment.type = AttachmentType.findByName("电话录音")
                attachment.riskWarning = riskWarning
                attachment.fileName = fileOrgName
                attachment.fileUrl = it
                attachment.description = fileOrgName?.split('\\.')[0]
                attachment.save(flush:true)
                i++
                println "第"+i+"条电话录音处理成功"
            }
        }
        //现场视频
        if(params?.lettersVideo){
            int i = 0
            params?.lettersVideo.each{
                String urlNameString = it
                def fileOrgName = urlNameString.split("\\/")[-1]
                Attachment attachment = new Attachment()
                attachment.type = AttachmentType.findByName("现场视频")
                attachment.riskWarning = riskWarning
                attachment.fileName = fileOrgName
                attachment.fileUrl = it
                attachment.description = fileOrgName?.split('\\.')[0]
                attachment.save(flush:true)
                i++
                println "第"+i+"条现场视频处理成功"
            }
        }
        //信函图片
        if(params?.lettersPicture){
            int i = 0
            params?.lettersPicture.each{
                String urlNameString = it
                def fileOrgName = urlNameString.split("\\/")[-1]
                Attachment attachment = new Attachment()
                attachment.type = AttachmentType.findByName("信函图片")
                attachment.riskWarning = riskWarning
                attachment.fileName = fileOrgName
                attachment.fileUrl = it
                attachment.description = fileOrgName?.split('\\.')[0]
                attachment.save(flush:true)
                i++
                println "第"+i+"条信函图片处理成功"
            }
        }

        //工作流推进
        if(params.taskNumber)
        {
            //按道理讲 还需要校验下 当前工作流状态才可以推进，要有stage
            def workflowInstance = WorkflowInstance.findByRiskWarningAndStatus(riskWarning, WorkflowInstanceStatus.findByName("Pending"))
            def map = workflowInstanceService.approve(workflowInstance, 'riskWarning')
            if (!map['flag']) 
            {
                render([message: map['message'], code: '2'] as JSON)
            }
        }
        render([message: "成功", code: '0'] as JSON)
    }


    //创建催收任务
    def aa(){
        def riskWarning = new com.cindata.RiskWarning()
        def map = [:]
        map.put("borrower",riskWarning?.mortgage?.mortgageContact?.fullName)
        map.put("borrowerPhone",riskWarning?.mortgage?.mortgageContact?.cellphone)
        map.put("breachNumber",riskWarning?.mortgage?.curDefaultingDuration)
        map.put("overdueNumber",riskWarning?.mortgage?.curOverdueDuration)
        map.put("planStartTime",riskWarning?.startTime)
        map.put("planEndTime",riskWarning?.endTime)
        map.put("taskNumber",riskWarning?.id)
        map.put("address",riskWarning?.mortgage?.mortgageContact?.address)
        map.put("orgId",riskWarning?.account?.id)
        map.put("goBackUrl","https://es02.cindata.cn/collectionApi/collectionCallBack")
    }


    // 读取请求的JSON参数
    private def readReqJSONParams(BufferedReader reader)
    {
        String line = null
        StringBuffer json = new StringBuffer()
        while ((line = reader.readLine()) != null)
        {
            json.append(line)
        }
        reader.close()
        def params = JSON.parse(json.toString())
        log.error("---------------->CollectionCallBack------------->json result is: ${params.inspect()}")
        return params
    }


    def createCollectionRecord(Attachment attachment,String url)
    {
        try{
        String urlNameString = url
        def fileOrgName = urlNameString.split("\\/")[-1]
        def fileType = fileOrgName?.split('\\.')[-1]
        fileType = fileType?.toLowerCase()

        def code = UUID.randomUUID().toString()
        URL realUrl = new URL(urlNameString)
        // 打开和URL之间的连接
        HttpURLConnection connection = (HttpURLConnection)realUrl.openConnection()
        connection.connect();
        // 获取所有响应头字段
        def appPath = servletContext.getRealPath("/").toString()
        def file = new File(servletContext.getRealPath("/"), "images/${code}.${fileType}")

        DataInputStream dataInputStream = new DataInputStream(connection.getInputStream());

        FileOutputStream fileOutputStream = new FileOutputStream(file);
        byte[] buffer = new byte[1024];
        int length;

        while ((length = dataInputStream.read(buffer)) > 0) {
            fileOutputStream.write(buffer, 0, length);
        }

        dataInputStream.close();
        fileOutputStream.close();
        println "fileName....."+file.getName()
        println file.exists()

        attachment.fileName = fileOrgName
        attachment.fileUrl = WebUtils.retrieveGrailsWebRequest().getBaseUrl() + "/static/images/${code}.${fileType}"

        attachment.description = fileOrgName?.split('\\.')[0]

        if (attachment.validate())
        {
            println "fileUrl:" + attachment.fileUrl
            attachment.save flush: true
        }
        else
        {
            println "失败"
            println attachment.errors
        }

        }catch (Exception e){
            e.printStackTrace()
        }
    }

}
